package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"

	"github.com/getlantern/systray"
)

func startTray() {
	systray.Run(onReady, onExit)
}

func onReady() {
	systray.SetTitle("Movie Tool")
	systray.SetTooltip("Movie Tool")

	menuOpen := systray.AddMenuItem("打开页面", "Open Web UI")
	menuPort := systray.AddMenuItem("端口设置", "Port Settings")
	menuFirewall := systray.AddMenuItem("添加防火墙", "Add Firewall Exception")
	menuRestart := systray.AddMenuItem("重启服务", "Restart Web Service")
	menuAutoStart := systray.AddMenuItemCheckbox("开机启动", "Auto Start", isAutoStart())
	menuQuit := systray.AddMenuItem("退出", "Exit Application")

	go startServer()

	for {
		select {
		case <-menuOpen.ClickedCh:
			openBrowser(fmt.Sprintf("http://localhost:%s", getCurrentPort()))
		case <-menuPort.ClickedCh:
			showPortDialog()
		case <-menuFirewall.ClickedCh:
			manualAddFirewall()
		case <-menuRestart.ClickedCh:
			restartApplication()
		case <-menuAutoStart.ClickedCh:
			toggleAutoStart(menuAutoStart)
		case <-menuQuit.ClickedCh:
			systray.Quit()
			return
		}
	}
}

func onExit() {}

func openBrowser(url string) {
	var err error
	switch runtime.GOOS {
	case "linux":
		err = exec.Command("xdg-open", url).Start()
	case "windows":
		err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
	case "darwin":
		err = exec.Command("open", url).Start()
	}
	if err != nil {
		log.Printf("Failed to open browser: %v", err)
	}
}

func showPortDialog() {
	htmlContent := fmt.Sprintf(`
<!DOCTYPE html>
<html>
<head>
    <title>端口设置</title>
    <style>body{font-family:Arial,sans-serif;padding:20px;background:#f5f5f5}.container{max-width:400px;margin:0 auto;background:white;padding:30px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1)}h1{text-align:center;color:#333;margin-bottom:30px}.form-group{margin-bottom:20px}label{display:block;margin-bottom:5px;font-weight:bold;color:#555}input[type="number"]{width:100%%;padding:10px;border:1px solid #ddd;border-radius:5px;box-sizing:border-box}button{background-color:#007bff;color:white;padding:12px 20px;border:none;border-radius:5px;cursor:pointer;font-size:16px;width:100%%}button:hover{background-color:#0056b3}.current-port{background-color:#f8f9fa;padding:15px;border-radius:5px;text-align:center;margin-bottom:20px}.note{font-size:12px;color:#666;margin-top:15px}</style>
</head>
<body>
    <div class="container">
        <h1>🔧 端口设置</h1>
        <div class="current-port"><strong>当前端口:</strong> %s</div>
        <form id="portForm">
            <div class="form-group">
                <label for="port">新端口 (1-65535):</label>
                <input type="number" id="port" name="port" min="1" max="65535" value="%s" required>
            </div>
            <button type="submit">💾 保存并重启</button>
        </form>
        <div class="note">
            <p>💡 提示: 修改端口后将自动重启服务</p>
            <p>⚠️ 注意: 端口号范围 1-65535，建议使用 1024 以上的端口</p>
        </div>
    </div>
    <script>
        document.getElementById('portForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const port = document.getElementById('port').value;
            const currentPort = '%s';

            fetch('/set-port', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'port=' + port
            }).then(response => {
                if (response.ok) {
                    return fetch('http://localhost:' + port + '/restart-server', { method: 'POST' });
                } else {
                    throw new Error('保存端口失败');
                }
            }).then(response => {
                if (response.ok) {
                    alert('端口已保存并重启服务！新端口: ' + port);
                    window.open('http://localhost:' + port, '_blank');
                    window.close();
                } else {
                    throw new Error('重启服务请求发送成功，但响应可能未收到。请检查新端口 ' + port + ' 是否正常工作。');
                }
            }).catch(error => {
                console.error('Error:', error);
                if (error.message.includes('Failed to fetch')) {
                    setTimeout(() => {
                        alert('端口已保存，但重启服务请求失败 (可能是新服务器正在启动或旧服务器未完全关闭)。请稍等片刻后手动访问新端口: http://localhost:' + port + ' 确认服务是否正常。');
                    }, 2000);
                } else {
                    alert('操作失败: ' + error.message);
                }
            });
        });
    </script>
</body>
</html>`, getCurrentPort(), getCurrentPort(), getCurrentPort())

	tempFile := filepath.Join(os.TempDir(), "port_setting.html")
	os.WriteFile(tempFile, []byte(htmlContent), 0644)
	openBrowser("file:///" + filepath.ToSlash(tempFile))
}

func isAutoStart() bool {
	switch runtime.GOOS {
	case "windows":
		return checkAutoStartWindows()
	case "linux":
		return checkAutoStartLinux()
	case "darwin":
		return checkAutoStartDarwin()
	default:
		return false
	}
}

func toggleAutoStart(mi *systray.MenuItem) {
	current := mi.Checked()
	if current {
		disableAutoStart()
		mi.Uncheck()
	} else {
		enableAutoStart()
		mi.Check()
	}
}

func enableAutoStart() {
	switch runtime.GOOS {
	case "windows":
		enableAutoStartWindows()
	case "linux":
		enableAutoStartLinux()
	case "darwin":
		enableAutoStartDarwin()
	}
}

func disableAutoStart() {
	switch runtime.GOOS {
	case "windows":
		disableAutoStartWindows()
	case "linux":
		disableAutoStartLinux()
	case "darwin":
		disableAutoStartDarwin()
	}
}

func enableAutoStartWindows() {
	execPath, _ := os.Executable()
	execPath = filepath.ToSlash(execPath)
	cmd := exec.Command("reg", "add", `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, "/v", "MovieTool", "/t", "REG_SZ", "/d", execPath, "/f")
	cmd.Run()
}

func disableAutoStartWindows() {
	cmd := exec.Command("reg", "delete", `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, "/v", "MovieTool", "/f")
	cmd.Run()
}

func checkAutoStartWindows() bool {
	cmd := exec.Command("reg", "query", `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, "/v", "MovieTool")
	err := cmd.Run()
	return err == nil
}

func enableAutoStartLinux() {}

func disableAutoStartLinux() {}

func checkAutoStartLinux() bool {
	return false
}

func enableAutoStartDarwin() {}

func disableAutoStartDarwin() {}

func checkAutoStartDarwin() bool {
	return false
}

func restartApplication() {
	log.Println("Sending restart signal from tray...")
	resp, err := http.Post("http://localhost:"+getCurrentPort()+"/restart-server", "application/json", nil)
	if err != nil {
		log.Printf("Error triggering server restart via HTTP: %v", err)
	} else {
		resp.Body.Close()
		log.Println("Restart signal sent via HTTP.")
	}
}